package com.mktech.taraservice.contentprovider;

import com.mktech.taraservice.db.DBHelper;
import com.mktech.taraservice.db.MovieDBManager;
import com.mktech.taraservice.db.base.BaseDBManager;
import com.mktech.taraservice.service.TaraApplication;
import com.mktech.taraservice.util.LogTool;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;

public class MyContentProvider extends ContentProvider
{

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs)
	{
		// TODO Auto-generated method stub
		int code = mUriMatcher.match(uri);
		switch (code)
		{
		case CODE_MOVIE_TABLE:
			int n = DBHelper.obtain(TaraApplication.getApp()).delete(MovieDBManager.TABLE_NAME, selection, selectionArgs);
			return n;
		default:
			break;
		}
		return 0;
	}

	@Override
	public String getType(Uri uri)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values)
	{
		// TODO Auto-generated method stub
//		LogTool.i("uri = "+uri);
		int code = mUriMatcher.match(uri);
		switch (code)
		{
		case CODE_MOVIE_TABLE:
			long rowId = DBHelper.obtain(TaraApplication.getApp()).insert(MovieDBManager.TABLE_NAME, values);
			if(rowId > 0)
			{
				Uri url = ContentUris.withAppendedId(uri, rowId);
				getContext().getContentResolver().notifyChange(url, null);
				return url;
			}
			break;
		default:
			break;
		}
		return null;
	}

	@Override
	public boolean onCreate()
	{
		// TODO Auto-generated method stub
		LogTool.i("onCreate");
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
	{
		// TODO Auto-generated method stub
		int code = mUriMatcher.match(uri);
		switch (code)
		{
		case CODE_MOVIE_TABLE:
			Cursor cusor = DBHelper.obtain(TaraApplication.getApp()).query(MovieDBManager.TABLE_NAME, projection, selection, selectionArgs, sortOrder);
			return cusor;
		default:
			break;
		}
		return null;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
	{
		// TODO Auto-generated method stub
		int code = mUriMatcher.match(uri);
		switch (code)
		{
		case CODE_MOVIE_TABLE:
			int n = DBHelper.obtain(TaraApplication.getApp()).update(MovieDBManager.TABLE_NAME, values, selection, selectionArgs);
			return n;
		default:
			break;
		}
		return 0;
	}

	private static final int CODE_MOVIE_TABLE = 0x100;

	private static UriMatcher mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	static
	{
		mUriMatcher.addURI(BaseDBManager.AUTHORIES, MovieDBManager.TABLE_NAME, CODE_MOVIE_TABLE);
	}

}
